/*
 * Compare if two matrices in binary files are identical, i.e. abs(a[i][j] - b[i][j]) < EPSILON.
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

#define EPSILON 0.001

int main(int argc, char **argv) {
   FILE *f1, *f2;
   float x1,x2;
   int count = 0;

   if (argc < 3) {
      fprintf(stderr,"Usage: %s <rawsource> <rawtarget> \n",argv[0]);
      exit(1);
   } 

   if ((f1 = fopen(argv[1],"r")) == NULL) {
      fprintf(stderr,"Cannot open file %s\n",argv[1]); 
      exit(1);
   }

   if ((f2 = fopen(argv[2],"r")) == NULL) {
      fprintf(stderr,"Cannot open file %s\n",argv[2]); 
      exit(1);
   }

   int ret1,ret2;
   while (!feof(f1) || !feof(f2)) {
      ret1 = fread(&x1,sizeof(float),1,f1);
      ret2 = fread(&x2,sizeof(float),1,f2);
      if ((ret1 == 0) && (ret2 == 0)) continue;
      if (ret1 != ret2) {
         fprintf(stderr,"Source or target file is too short\n"); 
         fprintf(stderr,"%d elements read\n",count); 
         exit(1);
      }
      //if (x1 != x2) {
      if (fabs(x1 - x2) > EPSILON) {
         printf("%d: %f <> %f\n",count,x1,x2);
      }
      count++;
   }
   printf("%d elements read\n",count); 
   fclose(f1);
   fclose(f2);
}
